;(function($, D) {
	//初始化参数
	var defaults = {
			id:'',									   // 显示日历的元素
            min: '1900-01-01',                          //最小日期
            max: '2099-12-31',                          //最大日期
            index: 2,                                   //显示多少个月份
            success: function (data){},                 //选择日历后执行的回调函数
            inTime: new Date().getTime(),               //初始化时候的租凭时间
            outTime: new Date().getTime() + 86400000,   //初始化时候的归还时间
            pointsAll: false,                           //是否日期全部可点
            show: function (data){},                    //显示的时候执行的回调函数【返回用户传入的参数】
            hide: function (data){}                     //隐藏的时候执行的回调函数【返回用户传入的参数】
	}, 
	suff = {
		checkDeadline:function(td,d, line, inTime){
			if( line.length < 1 ){
				return false;
			}
			for( var i = 0, len = line.length; i < len ; i++ ){
//				if( inTime != d ){
//			console.log( line[i] )
					if( d == line[i] ){
						if( td.classList.contains('date_nothis') ){
							td.classList.add('no_line');
						}else{
							td.classList.add('date_nothis');
							td.classList.add('no_line');
						}
					}
//				}else{
//					if( line[i] == inTime ){
//						td.classList.remove('date_td');
//					}
//				}
				
			}
			
			
		},
		chunkDate:function(){
			if( this.timeArr.length == 0 ){
				return false;
			}
			var td = document.querySelectorAll('td');
			var self = this;
			function noLineAll(d, i){
				mui.each(td, function(k){
					if( k >= i ){
						this.classList.add('sel_no_line');
					}
				})
			}
			if( this.timeArr.length == 1 ){
				//如果只点击一个日期，则检测当天之后的的日期有没有档期
				for( var i = 0 ; i < td.length ; i++ ){
					if( td[i].classList.contains('no_line') && td[i].getAttribute('data-ymd') > self.timeArr[0] ){
						noLineAll(td[i], i)
						break;
					}
				}
			}else{
				this.timeArr.sort();
				mui.each( td , function() {
					var ymd = this.getAttribute('data-ymd');
					if( ymd == self.timeArr[0] ){
						this.classList.add('first');
					}
					if( ymd > self.timeArr[0] && ymd < self.timeArr[1] ){
						this.classList.add('ins');
					}
					if( ymd == self.timeArr[1] ){
						this.classList.add('last');
					}
				});
			}
		},
		/**
         * 存放租赁和归还时间
         */
		timeArr:[],
		 /**
         * 月份数组
         */
        moth: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
		/**
         * 阻止事件冒泡
         * @param e  【事件的event对象】
         */
        stopPropagation: function (e){
            var event = e || window.e;
            event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
        },
		/*
		 * 创建日历布局容器
		 */
		createTable:function() {
			var tableHtmlArr = [];
			for( var i = 0 ; i < 6 ; i++ ){
                tableHtmlArr.push('<tr><td><span></span></td><td><span></span></td><td><span></span></td><td><span></span></td><td><span></span></td><td><span></span></td><td><span></span></td></tr>')
			}
			return tableHtmlArr.join('');
		},
		/*
		 * 创建顶部显示拦
		 */
		createDiv:function() {
            return '<div class="date_month"></div>';
		},
		/*
		 * 创建整体结构
		 */
		monthTem:function(index) {
			var tem = '', viewDOM, bc ='';
			tem = ''+ 
			'		<ul class="date_week_ul">'+
			'			<li>一</li>'+
			'			<li>二</li>'+
			'			<li>三</li>'+
			'			<li>四</li>'+
			'			<li>五</li>'+
			'			<li>六</li>'+
			'			<li>日</li>'+
			'		</ul>';
			for( var i = 0 ; i < index ; i++ ){
				if( i > 0 ){bc = 'date-ml4'}
				viewDOM = '' + 
				'<div class="date-box '+ bc+'">'+
				'	<div class="date_main">'+
				'		<div class="date_box-top">'+
				this.createDiv((i+1), index) +
				'		</div>'+
				'		<table class="ate_box_table" cellspacing="1" cellpadding="0">' +
				this.createTable() +
				'		</table>'+
				'	</div>'+
				'</div>';
				tem += viewDOM;
			}
			return tem;
		},
		/*
		 * 日历容器
		 */
		createDivBox : function(id, index) {
			var odiv = document.createElement('div');
			odiv.id = id + 'Box';
			odiv.innerHTML = this.monthTem(index);
			odiv.className = 'date_mainBox';
			document.querySelector('#'+id).appendChild(odiv);
			this.setHeight(odiv);
		},
		createDivBox2:function(id,index){
			var box = document.querySelector('#'+id+'Box');
			for( var i = 0; i < index ; i ++ ){
				var odiv = document.createElement('div');
				odiv.className = 'date-box date-ml4';
				odiv.setAttribute('data-ready', 1);
				var o = '	<div class="date_main">'+
					'		<div class="date_box-top">'+
					this.createDiv((i+1), index) +
					'		</div>'+
					'		<table class="ate_box_table" cellspacing="1" cellpadding="0">' +
					this.createTable() +
				'		</table>'+
				'	</div>';
				
				odiv.innerHTML = o;
				box.appendChild(odiv);
			}
		},
		setHeight:function(dom){
			var otd = dom.querySelectorAll('td');
//			otd[0].style.height = otd.offsetWidth + 'px';
			var otdthis = otd[0].offsetWidth;
			mui.each(otd, function(){
				this.style.height = otdthis + 'px';
			})
		},
		/*
		 * 判断是否为闰年
		 */
		isleap : function(year) {
			return ( year%4 === 0 && year%100 !== 0 ) || year%400 === 0;
		},
		/**
         * 渲染阳历节日
         */
		festival:function(td, md) {
			var str ; 
			switch(md) {
				case '1.1':
					str = '元旦';
					break;
				case '4.5':
					str = '清明';
					break;
				case '5.1':
					str = '劳动';
					break;
				case '10.1':
					str = '国庆';
					break;
			}
			str && (td.setAttribute('data-holiday', str), td.innerHTML = str, td.className += 'cRed');
			str = null;
		},
		 /**
         * 返回农历日期
         * @param yy
         * @param mm
         * @param dd
         */
		getCNDate:function (td, yy, mm, dd) {
			var that = this;
            var CalendarData=new Array(100);
            var madd = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
            var cYear,cMonth,cDay,TheDate;
            CalendarData = new Array(0xA4B,0x5164B,0x6A5,0x6D4,0x415B5,0x2B6,0x957,0x2092F,0x497,0x60C96,0xD4A,0xEA5,0x50DA9,0x5AD,0x2B6,0x3126E, 0x92E,0x7192D,0xC95,0xD4A,0x61B4A,0xB55,0x56A,0x4155B, 0x25D,0x92D,0x2192B,0xA95,0x71695,0x6CA,0xB55,0x50AB5,0x4DA,0xA5B,0x30A57,0x52B,0x8152A,0xE95,0x6AA,0x615AA,0xAB5,0x4B6,0x414AE,0xA57,0x526,0x31D26,0xD95,0x70B55,0x56A,0x96D,0x5095D,0x4AD,0xA4D,0x41A4D,0xD25,0x81AA5,0xB54,0xB6A,0x612DA,0x95B,0x49B,0x41497,0xA4B,0xA164B, 0x6A5,0x6D4,0x615B4,0xAB6,0x957,0x5092F,0x497,0x64B, 0x30D4A,0xEA5,0x80D65,0x5AC,0xAB6,0x5126D,0x92E,0xC96,0x41A95,0xD4A,0xDA5,0x20B55,0x56A,0x7155B,0x25D,0x92D,0x5192B,0xA95,0xB4A,0x416AA,0xAD5,0x90AB5,0x4BA,0xA5B, 0x60A57,0x52B,0xA93,0x40E95);

            function GetBit(m,n){
                return (m>>n)&1;
            }

            function e2c(){
                TheDate= (arguments.length!=3) ? new Date() : new Date(arguments[0],arguments[1],arguments[2]);
                var total,m,n,k;
                var isEnd=false;
                var tmp=TheDate.getYear();
                if(tmp<1900){
                    tmp+=1900;
                }
                total=(tmp-1921)*365+Math.floor((tmp-1921)/4)+madd[TheDate.getMonth()]+TheDate.getDate()-38;

                if(TheDate.getYear()%4==0&&TheDate.getMonth()>1) {
                    total++;
                }
                for(m=0;;m++){
                    k=(CalendarData[m]<0xfff)?11:12;
                    for(n=k;n>=0;n--){
                        if(total<=29+GetBit(CalendarData[m],n)){
                            isEnd=true; break;
                        }
                        total=total-29-GetBit(CalendarData[m],n);
                    }
                    if(isEnd) break;
                }
                cYear=1921 + m;
                cMonth=k-n+1;
                cDay=total;
                if(k==12){
                    if(cMonth==Math.floor(CalendarData[m]/0x10000)+1){
                        cMonth=1-cMonth;
                    }
                    if(cMonth>Math.floor(CalendarData[m]/0x10000)+1){
                        cMonth--;
                    }
                }
            }

            function GetLunarDay(solarYear, solarMonth, solarDay){
                if(solarYear<1921 || solarYear>2020){
                    return "";
                }else{
                    solarMonth = (parseInt(solarMonth)>0) ? (solarMonth-1) : 11;
                    e2c(solarYear,solarMonth,solarDay);
                    return GetcDateString();
                }
            }

            function GetcDateString(){
                var str,
                    md = cMonth + '.' + cDay;
                switch(md){
                    case '12.29':
                        that.tds = td;
                        that.dd = dd;
                        str = '除夕';
                        break
                    case '12.30':
                        that.tds.innerHTML = that.dd
                        that.tds.className = that.tds.className.replace(/cRed/, '')
                        that.tds.removeAttribute('data-holiday');

                        that.tds = null;
                        that.dd = null;

                        str = '除夕';
                        break;
                    case '1.1':
                        str = '春节';
                        break;
                    case '1.15':
                        str = '元宵';
                        break;
                    case '5.5':
                        str = '端午';
                        break;
                    case '8.15':
                        str = '中秋';
                        break;
                };

                str && (td.setAttribute('data-holiday', str), td.innerHTML = str, td.className += ' cRed');
                str = null;
            }

            GetLunarDay(yy, mm, dd)
		}
	};
	
	
	
	
	function oDate(options) {
		this.option = $.extend(defaults, options);
		//通用月份最后一天
		this.months = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		this.mins = this.option.min.match(/\d+/g); //存放最小年月日
        this.maxs = this.option.max.match(/\d+/g); //存放最大年月日
        return this;
	}
	oDate.prototype = {
		//初始化
		init:function() {
			var self = this, option = self.option;
			if( !option['id'] ){
				throw new Error("需要传入元素id");
				return false;
			}
			document.querySelector("#"+option.id).setAttribute('data-timein', option.inTime);
			document.querySelector("#"+option.id).setAttribute('data-timeout', option.outTime);
			//渲染控件
			this.view();
			this.initDOM(option.id, [
				parseInt(document.querySelector("#"+option.id).getAttribute('data-timein'), 10),
				parseInt(document.querySelector("#"+option.id).getAttribute('data-timeout'), 10)
			]);
			this.events(option.id);
			
		},
		//渲染控件
		view:function() {
			var option = this.option;
			if( option.index >= 6 ){option.index = 6}
			if( option.index <= 1 ){option.index = 1}
			suff.createDivBox(option.id, option.index);
			return this;
		},
		//初始化日历数据
		initDOM:function(id, ymd) {
			var log = {}, de = new Date(), option = this.option;
			var arr = ymd.sort(), oi = 0, oj = 1
				inDe = new Date( arr[0] ),
				outDe = new Date( arr[1] );
			var inTime = [inDe.getFullYear(), inDe.getMonth() + 1, inDe.getDate()],
				outTime = [outDe.getFullYear(), outDe.getMonth() + 1, outDe.getDate()];
			
			if( inTime[0] < this.mins[0]) {
				inTime[0] = this.mins[0];
			}
			if( outTime[0] < this.maxs[0] ){
				outTime[0] = this.maxs[0];
			}
			log.ymd = [inTime[0], inTime[1] - 1, inTime[2]];
			
			for( j = 0 ; j < option.index ; j++ ){
				
				//月份超过12月，年份加1 ；
				if( j > 0 ){
					log.ymd[1] += 1;
					if( log.ymd[1] >= 12 ){
						log.ymd[1] -= 12, log.ymd[0]++;
					}
				}
				
				//判断年份是否为闰年
				this.months[1] = suff.isleap(log.ymd[0]) ? 29:28;
				
				//获取当前月份1号是星期几
				var De = new Date();
				De.setFullYear(log.ymd[0], log.ymd[1], 1);
				log.FDay = De.getDay();

				//获取当前月份有多少天
				log.NDay = this.months[log.ymd[1]];
				
				//渲染日
				var dateMins = document.querySelectorAll('#' + id + 'Box .date-box')[j],
						tds  = dateMins.querySelectorAll('td'),
						DD 	 = 1, time
					getInTime = new Date( inTime[0], inTime[1] - 1, inTime[2] ).getTime(),
					getOutTime = new Date( outTime[0], outTime[1] - 1, outTime[2] ).getTime();
				var thatDe = new Date();
				log['thatTime'] = new Date(thatDe.getFullYear(), thatDe.getMonth(), thatDe.getDate()).getTime();
				for( var i = 0 ; i< tds.length; i++ ){
					tds[i].className = '';
					tds[i].innerHTML = '';
					tds[i].removeAttribute('data-ymd');
					if( i < log.FDay || i > ( log.NDay + log.FDay - 1 ) ){
						tds[i].className = 'date_nothis';
						continue;
					}
					tds[i].innerHTML = '<span>'+DD+'</span>';
					tds[i].querySelector('span').style.lineHeight = tds[i].offsetWidth + 'px';
//					suff.festival(tds[i], (log.ymd[1]+1) + '.' + DD);
//					suff.getCNDate(tds[i], log.ymd[0], (log.ymd[1]+1), DD);
					
					time = new Date(log.ymd[0], log.ymd[1], DD).getTime();
					 if (!option.pointsAll){
					 	tds[i].setAttribute('data-ymd', time);
					 	log['thatTime'] <= time ? tds[i].setAttribute('data-ymd', time) : tds[i].className = 'date_nothis';
//                      if (arg.days15){
//                          (o.timeArr[0] <= time && o.timeArr[0] + (15 * 86400000)) > time ? tds[i].setAttribute('data-ymd', time) : tds[i].className = 'date_nothis';
//                      }else{
//                          log['thatTime'] <= time ? tds[i].setAttribute('data-ymd', time) : tds[i].className = 'date_nothis';
//                      }

                    }else{
                        tds[i].setAttribute('data-ymd', time)
                    }
//					if (suff.timeArr.length === 1){
//                      if (suff.timeArr[0] === time){
//                          tds[i].className += ' date_td';
//                          tds[i].innerHTML = '归还';
//                      }
//                  }else{
                        if (time == getInTime){
                        		oi = i;
                        		oj = j;
//                          tds[i].className += ' date_td';
//                          suff.timeArr.push(time);
                        }

                        if (i == (oi+1) && oj == j){
//                          tds[i].className += ' date_td';
//                          tds[i].querySelector('span').innerHTML = '归还';
//                          suff.timeArr.push(time);
                        }
//                  }
					suff.checkDeadline(tds[i], time, this.option.deadline, getInTime);
                    DD++;
				}
				document.querySelectorAll('#'+id+'Box .date_month')[j].setAttribute('data-ym', log.ymd[0]+'-'+log.ymd[1]);
				document.querySelectorAll('#'+id+'Box .date_month')[j].setAttribute('data-time', time);
				document.querySelectorAll('#'+id+'Box .date_month')[j].innerHTML = '<span style="font-size:11px;color:#ddd;">' +log.ymd[0] + '</span> ' + suff.moth[log.ymd[1]] + '月 ' ;
			}
		
			this.option.initCall(this);
			
		},
		events:function(id){
			var option = this.option, that = this;
			
			document.querySelector('#' + id + 'Box').click(suff.stopPropagation);
			
			//清除状态
			mui('.calen-top').on('tap', '.'+option.clearBtn, function(){
				var td = D.querySelectorAll('td');
				mui.each(td, function() {
					 this.classList.remove('sel_no_line');
					 this.classList.remove('first');
					 this.classList.remove('last');
					 this.classList.remove('date_td');
					 this.classList.remove('ins');
					 suff.timeArr = [];
				});
				that.option.success({timer:[]}, that);
			});
			
			$('body').on('tap', '#'+id+'Box td', function() {
				var timestamp = parseInt(this.getAttribute('data-ymd'), 10);
				var outTime = null;
				//空日期
				if( this.classList.contains('date_nothis') || this.classList.contains('sel_no_line') ){return false;}
				
				if( suff.timeArr[0] && suff.timeArr[0] == timestamp ) { return false;}
				if( suff.timeArr.length > 1 ){
					suff.timeArr = [];
					var dateTD = D.querySelectorAll('#' + id + 'Box .date_td');
					for( var k = 0 ; k < dateTD.length ; k++ ){
						dateTD[k].classList.remove('date_td');
						dateTD[k].classList.remove('first');
						dateTD[k].classList.remove('last');
						var strTime = dateTD[k].getAttribute('data-ymd');
                        var Ds = new Date();
                        Ds.setTime(strTime);
                        dateTD[k].querySelector('span').innerHTML = Ds.getDate();
					}
				}
				var insTd = D.querySelectorAll('.ins');
				mui.each( insTd, function(){
					this.classList.remove('ins');
				});
				
				
				if( suff.timeArr.length == 0 ){
//					this.innerHTML = '租赁';	
					this.classList.add('date_td');
					var sel_no_line = D.querySelectorAll('.sel_no_line');
					mui.each( insTd, function(){
						this.classList.remove('sel_no_line');
					});
				}else{
//					this.innerHTML = '归还';	
					this.classList.add('date_td');
				}
				
				
				if( suff.timeArr && suff.timeArr[0] > timestamp ){
					suff.timeArr = [];
					D.querySelectorAll('.date_td')[1].classList.remove('date_td');
				}
				suff.timeArr.push(timestamp);
				if( suff.timeArr.length == 2 ){
					suff.timeArr.sort();
				}
				 suff.chunkDate();
				 option.success({timer:suff.timeArr}, that);
			});
		
		
		},
		addDate:function(func){
			var date_month = document.querySelectorAll('.date_month');
			var st = date_month[date_month.length-1].getAttribute('data-ym').match(/\d+/g);
			suff.createDivBox2(this.option.id, this.option.index);
			var y = parseInt(st[0], 10);
            var m = parseInt(st[1], 10);
            
			this.viewDate2({
				ymd: [y, m + 1, 1]
			},func); 
		},
		viewDate2:function(ymd, func){
			var box = document.querySelectorAll('[data-ready]'),
				len = box.length;
			var log = {}, De = new Date(), option = this.option;
			log['ymd'] = [ymd.ymd[0],ymd.ymd[1],ymd.ymd[2]];
			for( j = 0 ; j < len; j++ ){
				//月份超过12月，年份加1 ；
				if( j > 0 ){
					log.ymd[1] += 1;
					if( log.ymd[1] >= 12 ){
						log.ymd[1] -= 12, log.ymd[0]++;
					}
				}
				//判断年份是否为闰年
				this.months[1] = suff.isleap(log.ymd[0]) ? 29:28;
				
				//获取当前月份1号是星期几
				var De = new Date();
				De.setFullYear(log.ymd[0], log.ymd[1], 1);
				log.FDay = De.getDay();
//				console.log(bexta.jsonToString(log))
				//获取当前月份有多少天
				log.NDay = this.months[log.ymd[1]];
				//渲染日
				var dateMins = box[j],
						tds  = dateMins.querySelectorAll('td'),
						DD 	 = 1, time
					getInTime = new Date( ymd.ymd[0], ymd.ymd[1] - 1, ymd.ymd[2] ).getTime();
//					getOutTime = new Date( outTime[0], outTime[1] - 1, outTime[2] ).getTime();
				var thatDe = new Date();
				log['thatTime'] = new Date(thatDe.getFullYear(), thatDe.getMonth(), thatDe.getDate()).getTime();
				for( var i = 0 ; i< tds.length; i++ ){
					tds[i].className = '';
					tds[i].innerHTML = '';
					tds[i].removeAttribute('data-ymd');
					if( i < log.FDay || i > ( log.NDay + log.FDay - 1 ) ){
						tds[i].className = 'date_nothis';
						continue;
					}
					tds[i].innerHTML = '<span>'+DD+'</span>';
					tds[i].querySelector('span').style.lineHeight = tds[i].offsetWidth + 'px';
					time = new Date(log.ymd[0], log.ymd[1], DD).getTime();
					 if (!option.pointsAll){
					 	tds[i].setAttribute('data-ymd', time);
					 	log['thatTime'] <= time ? tds[i].setAttribute('data-ymd', time) : tds[i].className = 'date_nothis';
                    }else{
                        tds[i].setAttribute('data-ymd', time)
                    }
                        if (time == getInTime){
                        		oi = i;
                        		oj = j;
                        }

//                      if (i == (oi+1) && oj == j){
//                      }
//                  }
					suff.checkDeadline(tds[i], time, this.option.deadline, getInTime);
                    DD++;
				}
				box[j].querySelector('.date_month').innerHTML = '<span style="font-size:11px;color:#ddd;">' +log.ymd[0] + '</span> ' + suff.moth[log.ymd[1]] + '月 ' ;
				box[j].querySelector('.date_month').setAttribute('data-ym', log.ymd[0]+'-'+log.ymd[1]); 
				box[j].querySelector('.date_month').setAttribute('data-time', time);
				box[j].removeAttribute('data-ready');
			}
			func();
		}
	}
	
	
	function suffDate(options) {
		new oDate(options).init();
	}
	
	$.fn = $.extend({
		fullDate:suffDate
	}, $.fn);
	
})(mui, document);






